package com.example.js;

import android.annotation.SuppressLint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private WebView webView;
    private String  url = "file:///android_asset/js_content.html";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    @SuppressLint("JavascriptInterface")
    private void initView() {
        webView = findViewById(R.id.webView);
        webView.setVerticalScrollBarEnabled(true);
        webView.getSettings().setJavaScriptEnabled(true);

        webView.loadUrl(url);
        webView.addJavascriptInterface(new MyJavascriptInterface(),"AndroidWebView");
        webView.setWebViewClient(new WebViewClient());
    }
    private class MyJavascriptInterface{
        public MyJavascriptInterface() {

        }

        //在js中调用window.AndroidWebView.showInfoFromJs(name)，便会触发此方法。
        @JavascriptInterface
        public void showInfoFromJs(String name) {
            Toast.makeText(MainActivity.this, name, Toast.LENGTH_SHORT).show();
        }
    }

    public void sendInfoToJs(View view){
        //点击事件
        String msg = ((EditText) findViewById(R.id.input_et)).getText().toString();
        //调用js中的函数：showInfoFromJava(msg)
        webView.loadUrl("javascript:showInfoFromJava('" + msg + "','                 巴拉巴拉')");
    }
}
